<template>
    <el-row>
        <el-col v-for="(o, index) in 1" :key="o" :span="8" :offset="index > 0 ? 2 : 0">
            <el-card :body-style="{ padding: '0px' }" style="height: 500px; width: 500px;margin-left: 320px;">
                <div style="padding: 14px">
                    <span style="font-size: 20px;">支付</span>
                    <div class="bottom">
                        <br />
                        <br />
                        <time class="time" style="font-size: 14px;">距离二维码过期还剩
                            <span style="color: red;font-size: 20px;">{{ countdown }}</span>
                        </time>
                        <br />
                        <br />
                        <br />
                        <br />
                        <br />
                    </div>
                </div>
                <p style="margin-left: 190px;">支付总额：
                    <span style="color: red; font-size: 20px;">{{ reccourselData.courseCPrice }}</span>
                </p>
                <br />
                <br />
                <br />
                <el-button type="primary" round style="margin-left: 130px;" @click="updatepay()">确认支付</el-button>
                <el-button type="danger" round style="margin-left: 70px;" @click="backgo">取消支付</el-button>
                <!-- <img src="http://192.168.110.188:9000/video/a82eb966-6479-4afb-9a1c-050ca92ada89.jpg" class="images" /> -->
            </el-card>
        </el-col>
    </el-row>

    <el-dialog v-model="centerDialogVisible" title="Warning" width="30%" align-center>
        <span>当前订单已超时，请重新下单</span>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="backgo">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script>
import { ref, reactive, onMounted, onUnmounted, computed } from 'vue'
import { ElMessage } from "element-plus";
import axios from '../../api/index';
import { useRoute, useRouter } from 'vue-router';


// const currentDate = ref(new Date())
export default {
    setup() {
        const centerDialogVisible = ref(false)
        const route = useRoute();
        const router = useRouter();

        // 从localStorage中获取存储的JSON字符串  
        var userInfoJsonString = localStorage.getItem('userInfo');

        // 确保userInfoJsonString不是null，如果是null，那么将其设置为空字符串  
        if (userInfoJsonString === null) {
            userInfoJsonString = "{}";
        }
        // 解析JSON字符串为JavaScript对象  
        var userInfo = JSON.parse(userInfoJsonString);

        let token = localStorage.getItem('token');
        let longtoken = localStorage.getItem('longtoken');
        const reccourselData = ref({
            courseCPrice: '',
            createDate: '',
            goodId: '',
            orderNo: '',
            orderState: '',
        });
        const itemId = route.params.productId
        let countdownRef = ref(null);// 5分钟转换为秒，初始时间为300秒  
        let intervalId = null;
        const startTime = ref();
        onMounted(() => {
            //发起请求查看是否有该用户与该课程的等待状态下订单，有的话给出提示，不能创建订单，没有的话再创建订单
            axios.get('/order/findPayState', {
                params: {
                    userId: userInfo.id,
                    goodId: itemId
                },
                headers: {
                    token: token,
                    longtoken: longtoken
                }
            }).then(response => {
                if (response.code === 200) {
                    console.log(response.data);
                    reccourselData.data = response.data;
                    reccourselData.value.courseCPrice = response.data.courseCPrice;
                    reccourselData.value.createDate = response.data.createDate;
                    reccourselData.value.goodId = response.data.goodId;
                    reccourselData.value.orderNo = response.data.orderNo;
                    reccourselData.value.orderState = response.data.orderState;
                    console.log(reccourselData.data.courseCPrice);
                    const givenTime = response.data.createDate;
                    //获取订单创建的时间戳
                    const dateObj = new Date(givenTime);
                    const timestamp = dateObj.getTime();
                    startTime.data = timestamp / 1000;

                    //获取当前时间戳 
                    const currentTimestampInSeconds = Math.floor(Date.now() / 1000);

                    countdownRef.value = (startTime.data + 300) - currentTimestampInSeconds

                    if (countdownRef.value == 0 || countdownRef.value < 0) {
                        centerDialogVisible.value = true;
                    }
                }
            })
        })
        const updateCountdown = () => {
            countdownRef.value--; // 每秒减少1秒  
            if (countdownRef.value <= 0) {
                clearInterval(intervalId); // 倒计时结束，停止定时器  
                countdownRef.value = 0; // 显示0秒  
            }
        };

        onMounted(() => {
            intervalId = setInterval(updateCountdown, 1000); // 每秒更新一次倒计时  
        });

        onUnmounted(() => {
            clearInterval(intervalId); // 清除定时器，避免内存泄漏  
        });


        // 将倒计时格式化为分:秒的形式，并返回给模板显示  
        const formattedCountdown = computed(() => {
            const minutes = Math.floor(countdownRef.value / 60).toString().padStart(2, '0');
            const seconds = (countdownRef.value % 60).toString().padStart(2, '0');

            return `${minutes}:${seconds}`;

        });
        //发起请求将支付状态改为未支付，并且返回首页
        function backgo() {
            console.log(reccourselData.value.orderNo);
            axios.get('/order/updateOrderNoPay', {
                params: {
                    orderNo: reccourselData.value.orderNo
                },
                headers: {
                    token: token,
                    longtoken: longtoken
                }
            }).then(response => {
                if (response.code === 200) {
                    console.log(response.data);
                }
            })
            router.push("/index")

        }
        //修改状态为支付成功
        function updatepay() {
            axios.get('/order/updateState', {
                params: {
                    orderNo: reccourselData.value.orderNo,
                    userId: userInfo.id,
                    goodId: itemId
                },
                headers: {
                    token: token,
                    longtoken: longtoken
                }
            }).then(response => {
                if (response.code === 200) {
                    console.log(response.data);
                    ElMessage.success("支付成功")
                    router.push("/index")
                } else {
                    ElMessage.error("支付失败")
                }
            })
        }

        return {
            updatepay,
            backgo,
            centerDialogVisible,
            startTime,
            countdown: formattedCountdown,
            itemId,
            token,
            longtoken,
            reccourselData,
            route,
            router,
        };
    }
}
</script>
<style>
.time {
    font-size: 12px;
    color: #999;
}

.bottom {
    margin-top: 13px;
    line-height: 12px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.button {
    padding: 0;
    min-height: auto;
}

.images {
    width: 350px;
    display: block;
    height: 350px;
    margin-left: 72px;
}
</style>
